
#include "HttpCmdGetSqliteData.h"
#include "SysInfo.h"
#include "Log_Client.h"


CHttpCmdGetSqliteData::CHttpCmdGetSqliteData()
{
    ClearCmdLocalData();
}


CHttpCmdGetSqliteData::~CHttpCmdGetSqliteData()
{

}

void CHttpCmdGetSqliteData::ClearCmdLocalData()
{
    m_nCount = 0;
    m_strKeyWord = "";

}

bool CHttpCmdGetSqliteData::CheckParamVaild(const std::string &strReqMessage)
{
    /*
        {
            "Data": {
                "count": 15,
                "keyword": "OK"
            }
        }
    */

    neb::CJsonObject reqJsonObj(strReqMessage);
    neb::CJsonObject &dataJsonObj = reqJsonObj["Data"];

    // These Args are optional
    dataJsonObj.Get("count", m_nCount);
    dataJsonObj.Get("keyword", m_strKeyWord);

    return true;
}

bool CHttpCmdGetSqliteData::FillRspData(std::string &strRspData)
{
    std::string strResult;
    QueryLog(m_nCount, m_strKeyWord, strResult);

    // need some system helper functions
    neb::CJsonObject rspJsonObj;
    rspJsonObj.AddEmptySubObject("Data");
    neb::CJsonObject &dataJsonObj = rspJsonObj["Data"];

    // Split
    std::vector<std::string> vtResult;
    SplitString2List(strResult, '\n', vtResult);

    // -1: not include the title row
    dataJsonObj.Add("Lists Count", vtResult.size() - 1);

    dataJsonObj.AddEmptySubArray("Sqlite List");
    neb::CJsonObject &sqliteDataListObj = dataJsonObj["Sqlite List"];



    auto iter = vtResult.cbegin();
    for (; iter != vtResult.cend(); ++iter)
    {
        sqliteDataListObj.Add(*iter);
    }


    strRspData = rspJsonObj.ToString();

    return true;
}


bool CHttpCmdGetSqliteData::SplitString2List(const std::string &strOriginText, char keyChar, std::vector<std::string> &vtResult)
{    
    std::vector<std::string> vtLines;
    size_t pos = 0, found;
    // while ((found = strOriginText.find(keyChar, pos)) != string::npos) 
    while ((found = strOriginText.find(keyChar, pos)) != -1) 
    {
        vtLines.push_back(strOriginText.substr(pos, found - pos));
        pos = found + 1;
    }
    vtLines.push_back(strOriginText.substr(pos));

    vtResult = vtLines;

    return true;
}